//
//  CCDetailViewModel.m
//  Activity
//
//  Created by its on 15/5/18.
//  Copyright (c) 2015年 coco. All rights reserved.
//

#import "CCDetailViewModel.h"
#import "CCDEvice.h"
#import <AVOSCloud/AVOSCloud.h>
#import <OMPromises/OMPromise.h>
#import <OMPromises/OMDeferred.h>
#import <LinqToObjectiveC/NSArray+LinqExtensions.h>
#import "CCError.h"
@interface CCDetailViewModel()
@end

@implementation CCDetailViewModel
- (id) initWithActivityID:(NSString *)activityid activityAuthor:(NSString *)author {
  if (self = [super init]) {
    _activityid = activityid;
    _commentCount = @"0";
    _favoriteCount = @"0";
    _authorId = author;
    _attributeString = [[NSMutableAttributedString alloc] init];
  }
  return self;
}

- (RACSignal *) getdetail {
  return  [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
    OMDeferred *deferred1 = [OMDeferred deferred];
    AVQuery *query = [AVQuery queryWithClassName:@"activity"];
    [query getObjectInBackgroundWithId:self.activityid block:^(AVObject *object, NSError *error) {
      if ( error ) {
        [deferred1 fail: error];
      } else {
        [deferred1 fulfil: object];
      }
    }];
    
    OMDeferred *deferred2 = [OMDeferred deferred];
    AVQuery *favorateQuery = [AVQuery queryWithClassName:@"favorite"];
    [favorateQuery whereKey:@"activity" equalTo: self.activityid];
    [favorateQuery findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
      if ( error ) {
        [deferred2 fail: error];
      } else {
        [deferred2 fulfil: objects];
      }
    }];
    
    OMDeferred *deferred3 = [OMDeferred deferred];
    AVQuery *commentQuery = [AVQuery queryWithClassName:@"comment"];
    [commentQuery whereKey:@"activity" equalTo: self.activityid];
    [commentQuery countObjectsInBackgroundWithBlock:^(NSInteger number, NSError *error) {
      if ( error ) {
        [deferred3 fail: error];
      } else {
        [deferred3 fulfil: @(number)];
      }
    }];
    [[[OMPromise all:@[deferred1, deferred2, deferred3]] fulfilled:^(NSArray *result) {
      AVObject *object = result[0];
      NSArray *favorate = result[1];
      NSNumber *commentCount = result[2];
      self.commentCount = commentCount.description;
      self.imageArray = [object objectForKey:@"images"];
      [self.imageArray linq_select:^id(NSString *item) {
        return [NSString stringWithFormat:@"%@?/imageView/1/w/%lf/h/%lf/", item, DEVICEWIDTH, DEVICEWIDTH*0.8];
      }];
      self.activityTitle = [object objectForKey:@"title"];
      [self generateAtttributeNSString: object];
      favorate = [favorate linq_select:^id(AVObject *item) {
        return  [item objectForKey:@"activity"];
      }];
      self.favoriteCount = [NSString stringWithFormat:@"%d", favorate.count];
      if ( [favorate containsObject: self.activityid] ) {
        self.alreadyFavorite = @(YES);
      } else {
        self.alreadyFavorite = @(NO);
      }
      
      [subscriber sendNext:self];
      [subscriber sendCompleted];
    }] failed:^(NSError *error) {
      [subscriber sendNext: ERROR(2003)];
      [subscriber sendCompleted];
    }];
    
    return [RACDisposable disposableWithBlock:^{
      
    }];
  }];
}

- (RACSignal *) favorite {
  
  return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
    self.isfavoriting = YES;
    if ( ![AVUser currentUser])  {
      self.isfavoriting = NO;
      [subscriber sendNext: ERROR(4001)];
      [subscriber sendCompleted];
    } else if ( ![[AVUser currentUser] isAuthenticated] ) {
      self.isfavoriting = NO;
      [subscriber sendNext: ERROR(4002)];
      [subscriber sendCompleted];
    } else {
      AVObject *object = [AVObject objectWithClassName:@"favorite"];
      [object setObject:self.activityid forKey:@"activity"];
      [object setObject:[AVUser currentUser].objectId forKey:@"author"];
      @weakify(self);
      [object saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
        @strongify(self);
        if ( succeeded ) {
          self.isfavoriting = NO;
          self.alreadyFavorite = @(YES);
          self.favoriteCount = [NSString stringWithFormat:@"%d", self.favoriteCount.intValue+1];
          [subscriber sendNext:ERROR(4004)];
          [subscriber sendCompleted];
        } else {
          self.isfavoriting = NO;
          [subscriber sendNext:ERROR(4003)];
          [subscriber sendCompleted];
        }
      }];
    }

    return  [RACDisposable disposableWithBlock:^{
      [subscriber sendCompleted];
    }];
  }];
}

- (RACSignal *) cancelFavorite {
  return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
    self.isfavoriting = YES;
    if ( ![AVUser currentUser])  {
      self.isfavoriting = NO;
      [subscriber sendNext:ERROR(4001)];
      [subscriber sendCompleted];
    } else if ( ![[AVUser currentUser] isAuthenticated] ) {
      [subscriber sendNext: ERROR(4002)];
    } else {
      AVQuery *query = [AVQuery queryWithClassName: @"favorite"];
      [query whereKey:@"author" equalTo:[AVUser currentUser].objectId];
      [query whereKey:@"activity" equalTo:self.activityid];
      @weakify(self);
      @weakify(subscriber);
      [query getFirstObjectInBackgroundWithBlock:^(AVObject *object, NSError *error) {
        @strongify(subscriber);
        @strongify(self);
        if ( !error ) {
          [object deleteInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
            @strongify(subscriber);
            if ( error ) {
              [subscriber sendNext: ERROR(4005)];
              self.isfavoriting = NO;
              [subscriber sendCompleted];
            } else {
              [subscriber sendNext:ERROR(4007)];
              self.isfavoriting = NO;
              [subscriber sendCompleted];
              self.alreadyFavorite = @(NO);
              self.favoriteCount = [NSString stringWithFormat:@"%d", self.favoriteCount.intValue-1];
            }
          }];
        } else {
          [subscriber sendNext: ERROR(4006)];
        }
      }];
    }
    return  [RACDisposable disposableWithBlock:^{
      [subscriber sendCompleted];
    }];
  }];
}

- (void) generateAtttributeNSString:(AVObject *) object {
  
  NSString *title = [NSString stringWithFormat:@"%@\n\n",[object objectForKey:@"title"]];
  NSString *money = [NSString stringWithFormat:@"%@元 /",[object objectForKey:@"money"]];
  NSString *time =  [NSString stringWithFormat:@"%@ /",[object objectForKey:@"time"]];
  NSString *address = [NSString stringWithFormat:@"%@ /",[object objectForKey:@"address"]];
  NSString *people = [object objectForKey:@"people"];
  NSString *content = [NSString stringWithFormat:@"\n\n\n%@",[object objectForKey:@"content"]];
  NSAttributedString *titleAttribute = [[NSAttributedString alloc] initWithString:title
                                                                       attributes:@{NSFontAttributeName:[UIFont boldSystemFontOfSize:18],
                                                                                    NSForegroundColorAttributeName:RGB(120, 120, 120, 1)}];
  NSAttributedString *moneyAttribute = [[NSAttributedString alloc] initWithString:money
                                                                       attributes:@{NSForegroundColorAttributeName:RGB(120, 120, 120, 1),
                                                                                    NSFontAttributeName:[UIFont systemFontOfSize:14]
                                                                                    }];
  NSAttributedString *timeAttribute = [[NSAttributedString alloc] initWithString:time
                                                                      attributes:@{NSForegroundColorAttributeName:RGB(120, 120, 120, 1),
                                                                                   NSFontAttributeName:[UIFont systemFontOfSize:14]}];
  NSAttributedString *addressAttribute = [[NSAttributedString alloc] initWithString:address
                                                                         attributes:@{NSForegroundColorAttributeName:RGB(69, 179, 148, 1),
                                                                                      NSFontAttributeName:[UIFont systemFontOfSize:14],
                                                                                      NSLinkAttributeName:@""}];
  NSAttributedString *peopleAttribute = [[NSAttributedString alloc] initWithString:people
                                                                            attributes:@{NSForegroundColorAttributeName:RGB(120, 120, 120, 1),
                                                                                     NSFontAttributeName:[UIFont systemFontOfSize:14]}];
  NSAttributedString *contentAttribute = [[NSAttributedString alloc] initWithString:content
                                                                        attributes:@{NSForegroundColorAttributeName:RGB(120, 120, 120, 1),
                                                                                     NSFontAttributeName:[UIFont systemFontOfSize:14]}];

  [_attributeString insertAttributedString:titleAttribute atIndex:0];
  [_attributeString insertAttributedString:moneyAttribute atIndex:[title length]];
  [_attributeString insertAttributedString:timeAttribute atIndex:[title length] + [money length]];
  [_attributeString insertAttributedString:addressAttribute atIndex:[title length] + [money length] + [time length]];
  [_attributeString insertAttributedString:peopleAttribute atIndex:[title length] + [money length] + [time length] + [address length]];
  [_attributeString insertAttributedString:contentAttribute atIndex:[title length] + [money length] + [time length] + [address length] + [people length]];
}


- (void) dealloc {
  
}
@end
